import React, { useState, useEffect, useRef } from 'react';
import './index.scss'
import { Button, Segmented, Space, Select, Switch, Table, Typography } from 'antd';
import type { TableColumnsType, } from 'antd';
import type { PopconfirmProps } from 'antd';
import { message, Popconfirm } from 'antd';
import { Modal } from 'antd';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';
// 引用
import Navbar from '../../../components/navbar/navbar';
import { useAppDispatch, useAppSelector } from '../../../unit/Hooks';
import { EmpGetList } from '../../../api/index'
import { set_EmpList, del_Emp, add_Emp, edit_Emp, del_EmpAll, } from '../../../store/list/index'



// 类型
interface DataType {
  key: React.Key;
  stuName?: string;
  address?: string;
  stuNo?: string;
  className?: string;
  salary?: string;
  workCity?: string;
  expertiseName?: string;
  origin?: string;
  collegeName?: string;
  gradYear?: string;
  createdTime?: string;
}
function employment() {
  // 表格数据 获取数据
  const dispatch = useAppDispatch()
  useEffect(() => {
    (
      async () => {
        let res = await EmpGetList();
        // console.log('表格数据', res);
   
        dispatch(set_EmpList(res.data.data.result));

      }
    )()
  }, [])
  // 存取数据 渲染
  const list = useAppSelector(state => {
    return state.list.data
  })


  // 删除
  const confirm = (key: string) => {
    dispatch(del_Emp(key))
    message.success('确定删除');
  };
 

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    // console.log(e);
    message.error('确定取消');
  };
  //新增 编辑
  //Model对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title, setTitle] = useState('')
  const [key, setKey] = useState('')
  const [form] = Form.useForm();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //增加 
  const add = () => {
    showModal()
    setTitle('新增')
    form.resetFields();
  }

  // 编辑
  const edit = (values: any) => {
    showModal()
    setTitle('编辑')
    setKey(values.key)
    form.setFieldsValue({
      stuName: values.stuName,
      address: values.address,
      stuNo: values.stuNo,
      className: values.className,
      salary: values.salary,
      workCity: values.workCity,
      expertiseName: values.expertiseName,
      origin: values.origin,
      collegeName: values.collegeName,
      gradYear: values.gradYear,
      createdTime: values.createdTime,
    });
  }

  // 增加 编辑共用表单
  type FieldType = {
    key: string;
    createdTime?: string;
    stuName?: string;
    address?: string;
    stuNo?: string;
    className?: string;
    salary?: string;
    workCity?: string;
    expertiseName?: string;
    origin?: string;
    collegeName?: string;
    gradYear?: string;
  };

  const onFinish = (values: FieldType) => {
    if (title === '新增') {
      values.key = new Date().toLocaleString()
      dispatch(add_Emp(values))
    } else {
      values.key = key
      dispatch(edit_Emp(values))
    }
    // console.log('Success:', values);
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 上传

  // 下载


  //搜索
  const [filtedTable, setfiltedTable] = useState([])
  const goSearchs = (value: any) => {
    // console.log(value, '222');
    const filterData = list.filter((item: any) => {
      return (
        (value.stuName ? item.stuName.includes(value.stuName) : true) && (value.origin ? item.origin.includes(value.origin) : true) && (value.workCity && value.workCity.length ? value.workCity.some(city => item.workCity.includes(city)) : true)
      )
    })
    setfiltedTable(filterData)
    // console.log('搜索后数据', filterData);

  }
  useEffect(() => {
    setfiltedTable(list)
  }, [list])
  // 数据分类
  const columns: TableColumnsType<DataType> = [
    {
      title: '学号',
      dataIndex: 'stuNo',
      key: 'stuNo',
    },
    {
      title: '学生姓名',
      dataIndex: 'stuName',
      key: 'stuName',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '班级',
      dataIndex: 'className',
      key: 'className'
    },
    {
      title: '学院名称',
      dataIndex: 'collegeName',
      key: 'collegeName'
    },
    {
      title: '专业',
      dataIndex: 'expertiseName',
      key: 'expertiseName'
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime'
    },
    {
      title: '上班城市',
      dataIndex: 'workCity',
      key: 'workCity'
    },
    {
      title: '市场部',
      dataIndex: 'origin',
      key: 'origin'
    },
    {
      title: '毕业薪资',
      dataIndex: 'salary',
      key: 'salary'
    },
    {
      title: '毕业年份',
      dataIndex: 'gradYear',
      key: 'gradYear'
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => edit(record)}>查看</a>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record.stuNo)}
            onCancel={() => cancel}
            okText="Yes"
            cancelText="No"
          >
            <a>删除</a>
          </Popconfirm>
          <a onClick={() => edit(record)}>编辑</a>
        </Space>
      ),
    },
  ];
  // 选中状态 
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {

    // console.log('111', 111);

    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

   // 批量删除
  const allDel = () => {
    dispatch(del_EmpAll(selectedRowKeys)); //批量删除派发
    selectedRowKeys.length = 0;
  }
  console.log();

  return (
    <div className='employ'>
      <div className="top">
        <Navbar goSearch={goSearchs}></Navbar>
      </div>
      <div className="foot">
        <div className="btnBox">
          <Button type="primary" onClick={add}>新增毕业学生</Button>
          {/* 新增 model对话框 */}
          <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
              form={form}
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              style={{ maxWidth: 600 }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item<FieldType>
                label="学生学号"
                name="stuNo"
                rules={[{ required: true, message: 'Please input your stuNo!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="学生姓名"
                name="stuName"
                rules={[{ required: true, message: 'Please input your stuName!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="学生班级"
                name="className"
                rules={[{ required: true, message: 'Please input your className!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="毕业薪资"
                name="salary"
                rules={[{ required: true, message: 'Please input your salary!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="上班城市"
                name="workCity"
                rules={[{ required: true, message: 'Please input your workCity!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="专 业"
                name="expertiseName"
                rules={[{ required: true, message: 'Please input your expertiseName!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item<FieldType>
                label="市场部"
                name="origin"
                rules={[{ required: true, message: 'Please input your origin!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item<FieldType>
                label="学 院"
                name="collegeName"
                rules={[{ required: true, message: 'Please input your collegeName!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item<FieldType>
                label="创建时间"
                name="createdTime"
                rules={[{ required: true, message: 'Please input your createdTime!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item<FieldType>
                label="毕业年份"
                name="gradYear"
                rules={[{ required: true, message: 'Please input your gradYear!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
              </Form.Item>
            </Form>
          </Modal>
          <Button type="primary" onClick={allDel}>批量删除</Button>
          <Button type="primary">学生批量导入</Button>
          <Button type="primary">学生信息导出</Button>
        </div>
        {/* 表格行是否可选择 类 数据*/}

        <Table rowSelection={rowSelection} columns={columns} dataSource={filtedTable} scroll={{ x: 2000, y: 3000 }} rowKey={(record) => record.id} />
      </div>
    </div>
  )
}

export default employment
